package web

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"jk-webook/internal/domain"
	"jk-webook/internal/service"
	"net/http"
	"regexp"
	"time"

	"github.com/gin-gonic/gin"
)

// UserHandler 定义用户相关的路由
type UserHandler struct {
	svc      *service.UserService
	emailExp *regexp.Regexp
	codeSvc  *service.CodeService
}

func NewUserHandler(svc *service.UserService, codeService *service.CodeService) *UserHandler {
	emailRegexPattern := "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"
	return &UserHandler{svc: svc, codeSvc: codeService, emailExp: regexp.MustCompile(emailRegexPattern)}
}

//	func (u *UserHandler) RegisterUserRoutesV1(rg *gin.RouterGroup) {
//		rg.POST("/login", u.login)
//		rg.POST("/edit", u.edit)
//		rg.POST("/signUp", u.signUp)
//		rg.POST("/profile", u.profile)
//	}
func (u *UserHandler) RegisterUserRoutes(server *gin.Engine) {
	rg := server.Group("/v1/users")
	rg.POST("/login", u.loginJwt)
	rg.POST("/edit", u.edit)
	rg.POST("/signUp", u.signUp)
	rg.POST("/profile", u.profileJwt)

}

func (u *UserHandler) signUp(ctx *gin.Context) {
	type SingUpReq struct {
		Email           string `json:"email`
		ConfirmPassword string `json:confirmPassword`
		Password        string `json:"password`
	}

	var req SingUpReq
	//解析错误 直接写会 4xx错误 根据Content-Type解析你的数据
	if err := ctx.Bind(&req); err != nil {
		return
	}
	const (
		emailRegexPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"
	)
	ok, err := regexp.Match(emailRegexPattern, []byte(req.Email))
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}
	if !ok {
		ctx.String(http.StatusOK, "邮箱格式不对")
		return
	}
	//调用Service方法
	err = u.svc.SignUp(ctx, domain.User{Email: req.Email, Password: req.Password})
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}
	fmt.Printf("%v \n", req)
	ctx.String(http.StatusOK, "注册成功")

}
func (u *UserHandler) login(ctx *gin.Context) {

	var claims UserClaims
	claims.Uid = 123
	claims.RegisteredClaims = jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute)),
	}
	//jtw校验 设置登录状态
	token := jwt.NewWithClaims(jwt.SigningMethodES512, claims)
	signedString, err := token.SignedString([]byte("LqTDGcHOTdd1gNMoWe8TV7y9KwHSj4vl"))
	if err != nil {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	ctx.Header("x-jwt-token", signedString)
	ctx.String(http.StatusOK, "登录成功")
	return
}
func (u *UserHandler) edit(ctx *gin.Context) {

}
func (u *UserHandler) profile(ctx *gin.Context) {

}

func (u *UserHandler) loginJwt(context *gin.Context) {

}

func (u *UserHandler) profileJwt(ctx *gin.Context) {
	value, ok := ctx.Get("claims")
	if !ok {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	claims, ok := value.(*UserClaims)
	if !ok {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	println(claims.Uid)
}

type UserClaims struct {
	jwt.RegisteredClaims
	Uid int64
}
